<template>
  <wf-el-drawer title="批量导入" :visible.sync="visible" size="520px">
    <div class="org-import-box">
      <div class="org-import-box-item">
        <i class="fa fa-file-excel-o org-import-box-icon"></i>
      </div>
      <div class="org-import-box-item">
        <span class="org-import-box-text">下载通讯录模板，批量新增成员信息</span>
      </div>
      <div class="org-import-box-item">
        <el-button class="org-import-box-btn" @click="downloadTemplate">下载模板</el-button>
      </div>
    </div>
    <div class="org-import-box">
      <div class="org-import-box-item">
        <i class="el-icon-document org-import-box-icon"></i>
      </div>
      <div class="org-import-box-item">
        <span class="org-import-box-text">
          上传填写的员工信息表，仅支持xsl、xlsx格式的Excel文件
        </span>
      </div>
      <div class="org-import-box-item">
        <el-upload
          ref="upload"
          class="org-import-upload"
          action="customAction"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :on-remove="onUploadRemove"
          :limit="1"
        >
          <el-button class="org-import-box-btn">上传表格</el-button>
        </el-upload>
        <br />
        <el-progress
          v-if="visableProgress"
          :text-inside="true"
          :stroke-width="16"
          :percentage="percentage"
        ></el-progress>
      </div>
    </div>
    <div slot="footer">
      <el-button @click="hide">取消</el-button>
    </div>
    <import-user-error
      ref="importUserError"
      @on-download-error="downloadError"
      @on-close="beforeClose"
    />
  </wf-el-drawer>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { downloadTemplate, exportError, clearRecoad, importUsers } from '@/api/organization';
  import { downloadBlob } from '@/utils/download';
  import { isExcel } from '@/utils/regExpUtil';

  import ImportUserError from '../modal/ImportUserError';

  export default {
    components: { ImportUserError },
    data() {
      return {
        visible: false,
        organizationId: 0,
        deptId: 0,
        fileList: [],
        percentage: 10,
        timer: null,
        visableProgress: false,
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    methods: {
      onOpen(data) {
        const { organizationId, mainId } = data;
        this.organizationId = organizationId;
        this.deptId = mainId;
        this.fileList = [];
        this.visible = true;
      },
      hide() {
        this.visible = false;
        this.organizationId = 0;
        this.deptId = 0;
        this.fileList = [];
      },
      async downloadTemplate() {
        const res = await downloadTemplate();
        downloadBlob(res.data, res.filename);
      },
      beforeUpload(file) {
        const _isExcel = isExcel(file.name);
        if (!_isExcel) {
          this.$message.error('支持格式：xls、xlsx');
        }
        if (_isExcel) {
          this.onUpload(file);
        }
        return false;
      },
      onUploadRemove() {
        this.fileList = [];
      },
      showProgress() {
        this.visableProgress = true;
        this.timer = setInterval(() => {
          if (this.percentage <= 90) this.percentage += 1;
        }, 1000);
      },
      async onUpload(file) {
        let _flie = file;
        if (this.isClient) {
          const { electronReadFile } = require('@/utils/electronUpload');
          _flie = await electronReadFile(_flie.path);
        }
        this.showProgress();
        const formData = new FormData(); //创建form对象
        formData.append('file', _flie);
        formData.append('organizationId', this.organizationId);
        formData.append('deptId', this.deptId);

        const res = await importUsers(formData);
        clearInterval(this.timer);
        this.visableProgress = false;
        this.percentage = 10;
        const { data = null } = res;
        if (data) {
          this.fileList.push({
            name: file.name,
            url: data.filePath || '',
          });
          this.filePath = data.filePath || '';
        }
        this.onUploadSuccess(res);
      },
      onUploadSuccess(res) {
        const { status, data, message } = res;
        if (status === 200) {
          if (data && data.failSize > 0) {
            this.$refs['importUserError'].open(data);
          } else {
            this.$emit('import-success', res);
            this.$message({
              dangerouslyUseHTMLString: true,
              type: 'success',
              message: `导入成功<span style="color:#4AAE5F;">${
                (data && data.successSize) || 0
              }</span>条，已更新员工信息`,
            });
            this.hide();
          }
        } else {
          this.$message.error(message || '上传失败');
        }
      },
      onUploadProgress(progressEvent) {
        console.log(progressEvent);
      },
      async downloadError() {
        const res = await exportError({
          deptId: this.deptId,
          organizationId: this.organizationId,
        });
        res && downloadBlob(res.data, res.filename);
      },
      beforeClose() {
        clearRecoad({
          deptId: this.deptId,
          organizationId: this.organizationId,
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .org-import-box {
    text-align: center;
    padding: 30px;
    margin: 10px 0;
    background-color: #f8f8fa;
    border-radius: 5px;
  }
  .org-import-box-item {
    padding: 15px 0;
  }
  .org-import-box-icon {
    font-size: 40px;
    color: #4276ee;
  }
  .org-import-box-btn {
    width: 380px;
  }
  .org-import-box-text {
    color: #7f848b;
  }
</style>
